package com.stylefeng.guns.modular.mch.card.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.constant.factory.ConstantFactory;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;

import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.IdGenerator;
import com.stylefeng.guns.core.util.ToolUtil;

import com.stylefeng.guns.modular.system.model.CardTimecard;
import com.stylefeng.guns.modular.system.model.CardOncecard;
import com.stylefeng.guns.modular.system.model.CardRechargeLog;
import com.stylefeng.guns.modular.system.model.ClubAdmin;
import com.stylefeng.guns.modular.system.model.SettingCard;
import com.stylefeng.guns.modular.system.model.VipUser;
import com.stylefeng.guns.modular.system.warpper.CardTimecardWarpper;
import com.stylefeng.guns.rest.common.ReturnTip;
import com.stylefeng.guns.modular.mch.card.service.ICardCategoryService;
import com.stylefeng.guns.modular.mch.card.service.ICardRechargeLogService;
import com.stylefeng.guns.modular.mch.card.service.ICardTimecardService;
import com.stylefeng.guns.modular.mch.card.service.ISettingCardService;
import com.stylefeng.guns.modular.mch.member.service.IVipUserService;

/**
 * 会员时间卡控制器
 *
 * @author guiyj007
 * @Date 2018-06-22 16:45:03
 */
@Controller
@RequestMapping("/mch/card/timecard")
public class CardTimecardController extends BaseController {

    @Autowired
    private ICardTimecardService cardTimecardService;
    @Autowired
    private ICardCategoryService cardCategoryService;
    @Autowired
    private ICardRechargeLogService cardRechargeLogService;

    @Autowired
    private ISettingCardService settingCardService;
    @Autowired
    private IVipUserService vipUserService;
    
    /**
     * 获取会员时间卡查询统计表头
     */
    @RequestMapping(value = "/statHeader")
    @ResponseBody
    public Object statHeader() {
    	HttpServletRequest request = this.getHttpServletRequest();
    	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
     	}
     	
     	ArrayList<Map<String, Object>> listRet = new ArrayList<Map<String, Object>>();
     	listRet.add(cardTimecardService.statCountItem(clubId, 0));
     	listRet.add(cardTimecardService.statCountItem(clubId, 1));
     	listRet.add(cardTimecardService.statCountItem(clubId, 4));
     	listRet.add(cardTimecardService.statCountItem(clubId, 2));
     	listRet.add(cardTimecardService.statCountItem(clubId, 5));
     	listRet.add(cardTimecardService.statCountItem(clubId, 3));
     	
        return new ReturnTip(0, "成功", listRet);
    }
    
    /**
     * 获取会员时间卡列表
     */
     @RequestMapping(value = "/pagelist")
     @ResponseBody
     public Object pagelist() {
     	HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
      	Integer clubId = clubAdmin.getClubId();
      	if (ToolUtil.isEmpty(clubId)) {
      		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
      	}
     	//综合查询条件
     	HashMap<String, Object> mapCondition = new HashMap<>();
     	mapCondition.put("vipId", ToolUtil.toStr(request.getParameter("vipId"), null));
     	mapCondition.put("title", ToolUtil.toStr(request.getParameter("vipCardName"), null));
     	mapCondition.put("realname", ToolUtil.toStr(request.getParameter("vipName"), null));
     	mapCondition.put("cardNumber", ToolUtil.toStr(request.getParameter("cardNumber"), null));
     	mapCondition.put("membershipName", ToolUtil.toStr(request.getParameter("membershipName"), null));
     	
     	//查询范围表头
     	Integer cardStatus = Convert.toInt(request.getParameter("cardStatus"), 0);
     	
     	Page<CardTimecard> page = new PageFactory<CardTimecard>().defaultPage("id", "desc");
     	page = cardTimecardService.pageList(page, clubId, mapCondition, cardStatus);
         
     	Map<String, Object> ret = super.packForPannelTable(page);
     	
        return new ReturnTip(0, "成功", ret);
     }
     
     /**
      * 获取会员时间卡列表
      */
      @RequestMapping(value = "/list")
      @ResponseBody
      public Object list() {
      	HttpServletRequest request = this.getHttpServletRequest();
      	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
       	Integer clubId = clubAdmin.getClubId();
       	if (ToolUtil.isEmpty(clubId)) {
       		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
       	}
       	
      	Integer vipId = Convert.toInt(request.getParameter("vipId"));
      	Integer cardId = Convert.toInt(request.getParameter("cardId"), 0);

      	Wrapper<CardTimecard> ew = new EntityWrapper<>();
      	ew = ew.eq("club_id", clubId);
      	ew = ew.eq("vip_id", vipId);
      	if (!cardId.equals(0)) {
      		ew = ew.eq("id", cardId);
      	}
      	
      	List<Map<String, Object>> result = cardTimecardService.selectMaps(ew);
      	new CardTimecardWarpper(result).warp2();
      	
      	HashMap<String, Object> ret = new HashMap<>();
      	ret.put("list", result);
      	
        return new ReturnTip(0, "成功", ret);
      }
     
     /**
      * 新增+更新 教练
      */
     @RequestMapping(value = "/save")
     @ResponseBody
     public Object save() throws Exception {
    	/**
    	 * 验证token中的俱乐部信息
    	 */
     	HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return new ReturnTip(500, "俱乐部信息失效");
     	}
     	
     	/**
     	 * 入库对象构建
     	 */
     	Integer _id = Convert.toInt(request.getParameter("id"), 0);
     	Integer cardTypeId = Convert.toInt(request.getParameter("cardTypeId"), 0);
     	Integer membershipId = Convert.toInt(request.getParameter("membershipId"), 0);
     	Integer vipId = Convert.toInt(request.getParameter("vipId"), 0);
     	Integer autoOpenCardSwitch = Convert.toInt(request.getParameter("autoOpenCardSwitch"), 0);
     	
     	VipUser vipUser = null;
     	if (!vipId.equals(0)) {
     		vipUser = ConstantFactory.me().getVipInfoById(vipId);
     	} else {
     		return new ReturnTip(500, "会员ID跟踪失败，请从会员管理模块进行添加");
     	}
     	
     	Map<String, Object> mapEntity = new HashMap<>();
     	mapEntity.put("clubId", clubId);
     	mapEntity.put("id", _id);
     	mapEntity.put("vipId",  vipId);
     	
     	if (vipUser != null) {
     		mapEntity.put("realname", vipUser.getRealname());
     		mapEntity.put("phone", vipUser.getPhone());
     		mapEntity.put("cardNumber", vipUser.getCardNumber());
     	}
     	
     	mapEntity.put("title", Convert.toStr(request.getParameter("title")));
     	
     	mapEntity.put("frontMoneyStatus", Convert.toInt(request.getParameter("frontConsumeSwitchStatus")));
     	mapEntity.put("actualMoney", Convert.toBigDecimal(request.getParameter("money")));
     	mapEntity.put("retainage", Convert.toBigDecimal(request.getParameter("retainage")));
     	//充值天数，如果在自动开卡开关打开时，数据重置为0
     	mapEntity.put("expireDays", autoOpenCardSwitch.equals(0) ? Convert.toInt(request.getParameter("expireDays"), 0) : 0);
     	
     	mapEntity.put("autoOpenCardSwitch", autoOpenCardSwitch);
     	mapEntity.put("openCardTime", DateUtil.date2TimeStamp(Convert.toStr(request.getParameter("openCardTime")), "yyyy-MM-dd"));
     	mapEntity.put("expireTime", DateUtil.date2TimeStamp(Convert.toStr(request.getParameter("expireTime")), "yyyy-MM-dd"));
     	
     	mapEntity.put("remark", Convert.toStr(request.getParameter("remark")));
     	mapEntity.put("contractNumber", Convert.toStr(request.getParameter("contractNumber")));
     	mapEntity.put("contractId", Convert.toInt(request.getParameter("contractId")));
     	mapEntity.put("isUnitedCard", Convert.toInt(request.getParameter("isUnitedCard"), 0));
     	mapEntity.put("payMethod", Convert.toStr(request.getParameter("payMethod")));
     	mapEntity.put("actualInsertTime", DateUtil.date2TimeStamp(Convert.toStr(request.getParameter("cardInsertTime")), null));
     	
     	mapEntity.put("cardTypeId", cardTypeId);
     	mapEntity.put("cardTypeName", cardTypeId.equals(0) ? "" : cardCategoryService.selectById(cardTypeId).getTitle());
     	mapEntity.put("membershipId", membershipId);
     	mapEntity.put("membershipName", membershipId.equals(0) ? "" : ConstantFactory.me().getStaffSpecialNameById(membershipId));
     	mapEntity.put("sourceId", Convert.toInt(request.getParameter("source")));
     	
     	mapEntity.put("opeUserId", clubAdmin.getId());
     	mapEntity.put("opeUserName", ToolUtil.isEmpty(clubAdmin.getRealname()) ? clubAdmin.getRealname() : clubAdmin.getNickname());
     	
     	try {
     		boolean res = cardTimecardService.save(mapEntity);
     		if (res) {
     			return new ReturnTip(0, "成功");
     		} else {
     			return new ReturnTip(502, "失败");
     		}
		} catch (Exception e) {
			// TODO: handle exception
			return new ReturnTip(501, e.getMessage());
		}
     }

     

     /**
      * 删除
      */
     @RequestMapping(value = "/delete")
     @ResponseBody
     public Object delete() {
         HttpServletRequest request = this.getHttpServletRequest();
      	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
      	Integer clubId = clubAdmin.getClubId();
      	if (ToolUtil.isEmpty(clubId)) {
      		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
      	}
      	
      	Integer id = ToolUtil.toInt(request.getParameter("id"));
      	Wrapper<CardTimecard> ew = new EntityWrapper<>();
      	ew = ew.eq("id", id);
     	ew = ew.eq("club_id", clubId);
     	try {
     		cardTimecardService.delete(ew);
 		} catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 			return ResponseEntity.ok(new ReturnTip(501, "删除失败"));
 		}
     	return new ReturnTip(0, "操作成功");
     }

     /**
      * 详情
      */
     @SuppressWarnings("unchecked")
 	@RequestMapping(value = "/detail")
     @ResponseBody
     public Object detail() {
         HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
     	}
     	
     	//获取内容
     	Integer id = ToolUtil.toInt(request.getParameter("id"));
     	CardTimecard itemInDb = cardTimecardService.selectById(id);
     	
     	//验证合同所属俱乐部
     	if (ToolUtil.isEmpty(itemInDb.getClubId()) || !itemInDb.getClubId().equals(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(501, "访问受限"));
     	}
     	
     	Map<String, Object> mapRet = null;
 		try {
 			mapRet = ToolUtil.convertBean(itemInDb);
 		} catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
     	new CardTimecardWarpper(null).warpTheMap2(mapRet);
     	
     	return new ReturnTip(0, "成功",  mapRet);
     }
     
     /**
      * 根据卡id获取其开卡配置信息
      */
 	 @SuppressWarnings("unchecked")
	@RequestMapping(value = "/getSetting")
     @ResponseBody
     public Object getSetting() {
        HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
     	}
     	
     	//获取内容
     	Wrapper<SettingCard> ew = new EntityWrapper<>();
    	ew = ew.eq("club_id", clubId);
    	Map<String, Object> mapSetting = settingCardService.selectMap(ew);
     	if (ToolUtil.isEmpty(mapSetting)) {
     		try {
				mapSetting = ToolUtil.convertBean(new SettingCard());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
     	}
    	
    	mapSetting.put("deadStatus", 2);
//    	mapSetting.put("deadline", 0);	//忽略真实配置
    	mapSetting.put("deadlineStatus", 0);
    	mapSetting.put("timeCardType", "multi");
    	mapSetting.put("startCardTime", DateUtil.timeStamp());
    	mapSetting.put("startCardDate", DateUtil.getDay());
     	
     	return new ReturnTip(0, "成功",  mapSetting);
     }
 	 
 	/**
      * 后期开卡
      */
 	 @RequestMapping(value = "/openCard")
     @ResponseBody
     public Object openCard() {
        HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
     	}
     	
     	//获取内容
     	Integer id = ToolUtil.toInt(request.getParameter("id"));
     	CardTimecard cardTimecard = cardTimecardService.selectById(id);
     	
     	//验证信息是否存在
     	Integer currentTime = DateUtil.timeStamp();
     	try {
     		Wrapper<CardTimecard> ew = new EntityWrapper<>();
         	ew = ew.eq("club_id", clubId);
         	ew = ew.eq("id", id);
     		
         	cardTimecard.setOpenCardTime(currentTime);
         	if (cardTimecard.getAutoOpenCardSwitch().equals(0)) {
         		cardTimecard.setExpireTime(currentTime + cardTimecard.getExpireDays() * 86400);
         	}
         	
 			cardTimecardService.update(cardTimecard, ew);
 		} catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
     	
     	/**
		 * vip会员的时间卡统计字段同步
		 */
		vipUserService.resetTimeCardInfo(cardTimecard.getVipId());
     	return new ReturnTip(0, "成功");
     }
 	 
 	/**
      * 续费
      */
 	 @RequestMapping(value = "/renew")
     @ResponseBody
     public Object renew() {
        HttpServletRequest request = this.getHttpServletRequest();
     	ClubAdmin clubAdmin = (ClubAdmin) request.getAttribute("member");
     	Integer clubId = clubAdmin.getClubId();
     	if (ToolUtil.isEmpty(clubId)) {
     		return ResponseEntity.ok(new ReturnTip(500, "俱乐部信息失效"));
     	}
     	
     	//获取内容
     	Integer id = ToolUtil.toInt(request.getParameter("cardId"));
     	CardTimecard cardTimecard = cardTimecardService.selectById(id);
     	
     	Integer membershipId = Convert.toInt(request.getParameter("membershipId"), 0);
     	Integer vipId = Convert.toInt(request.getParameter("vipId"), 0);
     	Integer currentTime = DateUtil.timeStamp();
     	
     	Map<String, Object> mapEntity = new HashMap<>();
     	mapEntity.put("clubId", clubId);
     	mapEntity.put("vipId",  vipId);
     	mapEntity.put("title", cardTimecard.getTitle());
     	mapEntity.put("realname", cardTimecard.getRealname());
     	mapEntity.put("actualMoney", Convert.toBigDecimal(request.getParameter("money")));
     	
     	//充值天数，如果在自动开卡开关打开时，数据重置为0
     	Integer expireDays = Convert.toInt(request.getParameter("expireDays"), 0);
     	mapEntity.put("expireDays", expireDays);
     	mapEntity.put("expireTime", DateUtil.date2TimeStamp(Convert.toStr(request.getParameter("expireTime")), "yyyy-MM-dd"));
     	//如果设置了到期时间，以到期时间为准
     	if (ToolUtil.isNotEmpty(request.getParameter("expireTime"))) {
     		Integer intIntevalDays = ((Integer) mapEntity.get("expireTime") - cardTimecard.getExpireTime())/86400;
     		mapEntity.put("expireDays", intIntevalDays);
     		cardTimecard.setExpireTime((Integer) mapEntity.get("expireTime"));
     	} else {
     		cardTimecard.setExpireTime(cardTimecard.getExpireTime() + expireDays * 86400);
     		cardTimecard.setExpireDays(cardTimecard.getExpireDays() + expireDays);
     	}
     	
     	mapEntity.put("remark", Convert.toStr(request.getParameter("remark")));
     	mapEntity.put("contractNumber", Convert.toStr(request.getParameter("contractNumber")));
     	mapEntity.put("contractId", Convert.toInt(request.getParameter("contractId")));
     	mapEntity.put("payMethod", Convert.toStr(request.getParameter("payMethod")));
     	mapEntity.put("actualInsertTime", currentTime);
     	mapEntity.put("cardTypeId", cardTimecard.getCardTypeId());
     	mapEntity.put("cardTypeName", cardTimecard.getCardTypeName());
     	mapEntity.put("membershipId", membershipId);
     	mapEntity.put("membershipName", membershipId.equals(0) ? "" : ConstantFactory.me().getStaffSpecialNameById(membershipId));
     	mapEntity.put("sourceId", Convert.toInt(request.getParameter("source")));
     	mapEntity.put("opeUserId", clubAdmin.getId());
     	mapEntity.put("opeUserName", clubAdmin.getRealname());
     	
     	try {
     		//卡更新
 			cardTimecardService.updateById(cardTimecard);
 			//重置记录流水添加
 			CardRechargeLog cardRechargeLog = (CardRechargeLog) ToolUtil.convertMap(CardRechargeLog.class, mapEntity);
			cardRechargeLog.setLogType(1);	//针对卡的类型 1 时间卡 2私教卡 3次卡 4储值卡
			cardRechargeLog.setPort(2);	//端口 1 充值新卡 2 续费
			cardRechargeLog.setIsRenewCard(1);	//是否续卡(1续卡 2启用 0新卡及其他)
			cardRechargeLog.setId(null);
			cardRechargeLog.setInsertTime(currentTime);
			cardRechargeLogService.insert(cardRechargeLog);
			
 		} catch (Exception e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
     	
     	/**
		 * vip会员的时间卡统计字段同步
		 */
		vipUserService.resetTimeCardInfo(cardTimecard.getVipId());
     	return new ReturnTip(0, "成功");
     }
 	 
}
